package com.reebake.ideal.storage.controller;

import com.reebake.ideal.storage.service.FileDetailService;
import com.reebake.ideal.storage.util.StorageUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.dromara.x.file.storage.core.FileInfo;
import org.dromara.x.file.storage.core.FileStorageService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.OutputStream;

@RestController
@RequestMapping("/storage/file")
public class FileDownloadController {
    @Autowired
    private FileStorageService fileStorageService;//注入实列
    @Autowired
    private FileDetailService fileDetailService;

    @GetMapping("download")
    public ResponseEntity<Void> view(String fileDetailId, HttpServletRequest request, HttpServletResponse response) {
        String dispositionType = "inline";
        // 获取文件信息
        FileInfo fileInfo = StorageUtil.toFileInfo(fileDetailService.getById(fileDetailId));
        String originalFilename = fileInfo.getOriginalFilename();
        fileStorageService.download(fileInfo).inputStream(in -> {
            byte[] buffer = new byte[1024];
            int len = 0;
            try {
                OutputStream os = response.getOutputStream();
                while ((len = in.read(buffer)) != -1) {
                    os.write(buffer, 0, len);
                }
            }catch (Exception e) {
                throw new RuntimeException(e);
            }
        });

        return ResponseEntity.ok()
                .header("Content-Disposition", dispositionType + "; filename=\"" + originalFilename + "\"")
                .header("Content-Type", fileInfo.getContentType())
                .header("Content-Length", "" + fileInfo.getSize())
                .build();
    }
}
